package com.qc31.monitorlib.base

import android.Manifest
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.Lifecycle
import androidx.viewbinding.ViewBinding
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider
import autodispose2.autoDispose
import com.amap.api.maps.AMap
import com.qc31.baselib.utils.showToast
import com.qc31.baselib.R
import com.qc31.baselib.utils.toast
import com.qc31.monitorlib.uitls.MapUtil
import com.tbruyelle.rxpermissions3.RxPermissions

abstract class BaseMapLocationActivity<VB : ViewBinding>(inflater: (LayoutInflater) -> VB) :
    BaseMapActivity<VB>(inflater), AMap.OnMyLocationChangeListener {
    //1.多车监控  2.区域查车  3.周边导航
    var type = 1

    private var isFirst = true
    private val mPermission: RxPermissions by lazy { RxPermissions(this) }
    private val locationManager by lazy {
        getSystemService(Context.LOCATION_SERVICE) as LocationManager
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mAMap.setOnMyLocationChangeListener(this)
    }

    private var isShow = false
    fun getPermissions(isShow: Boolean = false) {
        this.isShow = isShow
        isFirst = true

        mPermission.requestEachCombined(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ).autoDispose(
            AndroidLifecycleScopeProvider.from(
                this@BaseMapLocationActivity,
                Lifecycle.Event.ON_DESTROY
            )
        ).subscribe {
            if (it.granted) {
                initGPS()
            } else {
                showToast(R.string.toast_no_has_permission)
            }
        }
    }


    /** 监听GPS */
    protected open fun initGPS() {
        val locationManager =
            this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (isFirst) {
                // 转到手机设置界面，用户设置GPS
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                // 设置完成后返回到原来的界面
                launcherLocation.launch(intent)
            } else {
                R.string.toast_open_location_info.toast(this)
            }

        } else {
            MapUtil.setLocationStyle(mAMap, isShow)
        }
    }


    private val launcherLocation = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) {
        isFirst = false
        initGPS()
    }


}